# Usage is pythonTestDriver.py TestThroughPackage.m [executable directory]
#       If executable directory is omitted default directory defined in 
#	TestThroughPacakge.m (created using TestThroughPackage.nb) is used.
#       Script now changes current working directory to that of the mathematica package before running package
from time import clock
from subprocess import Popen, PIPE
from sys import argv
import os
t1=clock()
path_to_math = r"c:\Program Files\Wolfram Research\Mathematica\7.0\math.exe"

if not (len(argv) == 2 or len(argv) == 3):
    print "Usage is pythonTestDriver.py Package.m [executable directory]"
    exit() 

package_dir, package_fn  = os.path.split(os.path.abspath(argv[1]))
os.chdir(package_dir)
print "working directory for package is:", os.getcwd()
math_cmds = open(package_fn).read()

if len(argv) == 2:
    print "using default executable directory defined in package"

if len(argv) == 3:
    exe_dir = os.path.abspath(argv[2])
#    s = r'exeDir = ToFileName["D:\\Wes\\mathdaq_test\\trunk\\build_MinGW\\Release"]' + '\n'
    s = r'exeDir = ToFileName[%r]' % exe_dir + '\n'
    s = s.replace("'", '"')   # Mathematica only accepts double quotes
    print "Executable directroy from command line is: %s" % exe_dir
    math_cmds = s + math_cmds

#math_cmds = r'exeDir = ToFileName["D:\\Wes\\mathdaq_test\\trunk\\build_MinGW\\Release"]' + '\n' + math_cmds

p = Popen([path_to_math], stdout=PIPE, stdin = PIPE, shell = True) 
out, err = p.communicate(math_cmds)
t2=clock()
print "*"*100 + "\n"
lines = []
for line in out.split("\r\n"):
	try:
		if line.rstrip() == "" or line.rstrip() [-1]=="=":
			continue
		lines.append(line)
	except IndexError, e:
		print "Exception"
		print repr(line)
		print e
print "\n".join(lines)
print file("logtest.txt").read()

if err == None:
	print "no message from stderr"
else:
	print "Message from stderr follows"
	print err

print "Running the package %s took %.2f seconds" %(argv[1], t2-t1)
print "*"*60
print lines[-2]
print lines[-1]
print "*"*60 + "\n"